from sanic.views import HTTPMethodView
from sanic.response import text,json
import urllib3
import json as jn


class wechatLogin(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        html_data = request.json
        client_ip = request.ip
        appid = 'wx5ad1de89ad1ea149'
        appsecret = '016b50a4bb754f24e293767d006e0c22'
        openid = ''
        try:
            # 查询商家
            sql = """
                    select user_id,wx_config from a_users where USER_SERVICE_TOKEN=%s and status='normal'
                """
            user_id = db.find_one(sql, (html_data['USER_SERVICE_TOKEN']))

            wx_config = user_id[1]
            user_id = user_id[0]

            if wx_config:
                wx_config = jn.loads(wx_config)
                appid = wx_config['Appid']
                appsecret = wx_config['Appsecret']

            if user_id:

                # 微信接口服务地址
                base_url = 'https://api.weixin.qq.com/sns/jscode2session'
                # 微信接口服务的带参数的地址
                url = base_url + "?appid=" + appid + "&secret=" + appsecret + "&js_code=" + html_data[
                    'code'] + "&grant_type=authorization_code"
                http = urllib3.PoolManager()
                resp = jn.loads(http.request('GET', url).data)
                openid = resp['openid']

                # 查询用户是否注册
                sql_register = """
                           select openid from c_users where merchant_id=%s and openid=%s
                       """

                register_show = db.find_one(sql_register, (user_id, openid))

                if register_show:
                    return json({'code': 200, 'message': "登录成功！"})
                else:
                    wechat_sql_insert = """
                            insert into c_users(merchant_id,openid,nickName,age,gender,head_img,phone,config,status,create_time ) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,now())
                        """
                    db.insert(wechat_sql_insert, (user_id, openid, '微信用户', '0', '0',
                                                  'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2F9e8bd863-bf16-4647-abf0-88490ce78ced%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1692239797&t=a656713f3185954147d0d361bef4b02d',
                                                  '', '', 'normal'
                                                  ))

                    return json({'code': 200, 'message': "注册成功！"})
            else:
                return json({'code': 401, 'message': "授权码无效！"})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/wechat/login', error))
            if openid:
                return json({'code': 500, 'message': "后端代码出错！"})
            else:
                return json({'code': 500, 'message': "appid或serct不对！"})